#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include "uart.h"
#include "config.h"
#include "lcd_driver.h"
#include "ioAT89S52.h"

volatile bool g_UARTReady = false;

void InitTimer1()
{
  //Config timer 1
  TMOD_bit.C_T1 = 0;  // Set as timer
  TMOD_bit.GATE1 = 0; //TR1�������� ֹͣ
  TMOD_bit.M01 = 0;
  TMOD_bit.M11 = 1;
  //TL1 = 0;
  TH1 = 0xfd;
  //����Timer 1
  TCON_bit.TR1 = 1;
}

void InitUART(void)
{
  //UART
  PCON_bit.SMOD = 1; //����baud X 2

  //8BIT MODE2
  SCON_bit.SM0 = 0;
  SCON_bit.SM1 = 1;

  SCON_bit.SM2 = 0; // �رնദ����
  SCON_bit.REN = 1;

  //Config Use timer 1 as closk source
  T2CON_bit.TCLK = 0; // Use Timer1
  T2CON_bit.RCLK = 0;

  InitTimer1();
  // ��UART�ж�
  IE_bit.ES = 1;

  g_UARTReady = true;
}

volatile uint8_t isDataRecvDone = 0;

void SendSync(const char *msg)
{
  const char *p = msg;
  while (*p != '\0')
  {
    while (!g_UARTReady)
      ;
    g_UARTReady = false;
    SBUF = *p;
    p++;
  }
}

void SendCharSync(const char msg)
{
  while (!g_UARTReady);
  g_UARTReady = false;
  SBUF = msg;
}

volatile uint8_t uartReciveStatus = UART_STATUS_INSTRUCTION;
volatile uint8_t RecvBuff[RECV_BUFF_LEN];
volatile uint16_t uartBuffIndexOrDirectSendLengthLeft = 0;

bool isEventReady(){
  return uartReciveStatus == UART_EVENT_READY;
}

void SetUARTRecvStatus(uint8_t status){
  uartReciveStatus = status;
}


#pragma vector = sio_ti
//#pragma vector = sio_ri
__interrupt void serial_RI(void)
{
  if (SCON_bit.RI == 1) /* clear reception flag for next reception */ /* if reception occur */
  {
    uint8_t receivedData = SBUF; /* Read receive data */
    SCON_bit.RI = 0;

    if (uartReciveStatus == UART_STATUS_INSTRUCTION)
    {
      if (receivedData == '\r')
      {
        uartReciveStatus = UART_EVENT_READY;
      }
      else if (uartBuffIndexOrDirectSendLengthLeft < RECV_BUFF_LEN)
      {
        RecvBuff[uartBuffIndexOrDirectSendLengthLeft] = receivedData;
        uartBuffIndexOrDirectSendLengthLeft++;
      }
      else{
        uartReciveStatus = UART_EVENT_READY;
      }
    }
    else if (uartReciveStatus == UART_STATUS_DATA)
    {
      if (uartBuffIndexOrDirectSendLengthLeft > 0)
      {
        LCD19264Write(receivedData);
        uartBuffIndexOrDirectSendLengthLeft--;
      }
      else
      {
        uartReciveStatus = UART_STATUS_INSTRUCTION;
        isDataRecvDone = 1;
      }
    }
  }

  if (SCON_bit.TI == 1)
  {
    SCON_bit.TI = 0; // clear emission flag for next emission
    g_UARTReady = true;
  }
}